$(function () {
  $.get('cats.action',"",processCatsResponse);
});

function processCatsResponse(data, status) {
  var sellerCats = data.sellerCats;
  var sellerCatsSelect = "<option value='all_cats'>---所有宝贝---</option>";
  var sellerCatsCheckbox = '';
  var ckb_style = "input_align_5";
  var count = 1;
  $.each(sellerCats, function (catref, cat) {
    var cat_name = cat.name;
    var seller_cats_checkbox_style ='seller_cats_checkbox2';
    if(cat.isLeaf=='2'){
      cat_name = '└'+cat.name;
    }
    if(cat.isLeaf=='0'){
      sellerCatsSelect += "<optgroup label="+ cat_name + "></optgroup>";
    }else{
      if(count!==1) {
      	ckb_style = "input_align_5 input_margin_20";
      }
      sellerCatsSelect += "<option value='" + cat.cid + "'>"+ cat_name + "</option>";
      sellerCatsCheckbox += "<input type='checkbox' class='"+ckb_style+"' name='seller_cats_promote' value='"+cat.cid+"'/>";
      sellerCatsCheckbox += cat.name;
      count = count + 1;
    } 
  });
  sellerCatsSelect += "<option value ='-1'>未分类宝贝</option>";
  $("#sellerCats").html(sellerCatsSelect);
  $("#sellerCats_2").html(sellerCatsSelect);
  $("#seller_cats_promote_div").html(sellerCatsCheckbox);
}
 
function to_step(step) {
	$('.tab'+step).click();
	window.location.href=window.location.href+'#tab'+step;
}

function buildSimpleTitle(ret){
  var title = ret.frank_title;
  if(title.length>10){
     title= title.slice(0, 5)+"..."+title.slice(-2);
  }
  var item_url = 'http://item.taobao.com/item.htm?id='+ret.iid;
  var title_html="<a href='"+item_url+"' style='text-decoration:underline;font-size:13px;color:blue;height:35px'>"+title+"</a>";
  return title_html;
}

function delete_allitems() {
	$(".bePromoted").each(function () {
	    var iid = $(this).attr("id");
	    $("#" + iid).remove();
  	});
  	$("#gridTable").jqGrid("resetSelection");
  	$("#choosed_item_container").css("display", "none");
}

function delete_item(iid)
{
	$("#"+iid).remove();
  	reset_gridtable_selection("item_list_table"); // 重新设置表格中的选择
}

function reset_time() {
	$("input[name='effect_date']").val("");
	$("input[name='expire_date']").val("");
}

function reset_gridtable_selection(grid_table_id) {
  var rownum = $("#"+grid_table_id).jqGrid("getGridParam", "rowNum");
  if(rownum==null){
    return;
  }
  $("#"+grid_table_id).jqGrid("resetSelection");
  $(".bePromoted").each(function () {
    var iid = $(this).attr("id");
    for (var i = 1; i <= rownum; i=i+1) {
      var ret = $("#"+grid_table_id).jqGrid("getRowData", i);
      if (ret.iid == iid) {
        $("#"+grid_table_id).setSelection(i);
      }
    }
  });
}

function setGridTableSelection() {
  var rownum = $("#gridTable").jqGrid("getGridParam", "rowNum");
  if(rownum==null){
    return;
  }
  $("#gridTable").jqGrid("resetSelection");
  $(".bePromoted").each(function () {
    var iid = $(this).attr("id");
    for (var i = 1; i <= rownum; i=i+1) {
      var ret = $("#gridTable").jqGrid("getRowData", i);
      if (ret.iid == iid) {
        $("#gridTable").setSelection(i);
      }
    }
  });
}


function sub_itemchoose_action(iids, action){
  var data={"iids": iids, "a": action };
  $.post("choose.action",data,null,'json');
}

function insert_iids(iid) {
	var iids = $("#iids_hidden").val();
	if(iids===undefined || iids===null || iids==="") {
		$("#iids_hidden").val(iid);
		return;
	}
	if(iids.indexOf(iid)>=0) return;
	else $("#iids_hidden").val(iids+","+iid);
}

function remove_iids(iid) {
	var iids = $("#iids_hidden").val();
	var iids_array = iids.split(iid);
	iids = "";
	for(var i=0; i<iids_array.length; i=i+1) {
		if(iids_array[i].charAt(0)==',')
			iids += iids_array[i].substr(1);
		else iids += iids_array[i];
	}
	if(iids.charAt(iids.length-1)==',') 
		iids = iids.substr(0, iids.length-1);
	$("#iids_hidden").val(iids);
}

function buildItemJsonStr(div_clazz){
	var clazz = "bePromoted";
	if(!empty(div_clazz)) clazz = div_clazz;
    var iItems = "";
    $('.'+clazz).each(function() {
      var iid = $(this).attr('id');
      var price = $(this).attr('price');
      var title = $(this).attr('item_title');
      if(title.length>25){
	     title= title.slice(0, 15)+"..."+title.slice(-10);
	  }
      var img = $("#" + iid + ' img');
      var pic_url = img.attr('src');

      var item='{"iid":"'+iid+'","title":"'+title+'","pic_url":"'+pic_url+'","price":"'+price+'"},';
      iItems+=item;
    });
    if(iItems!=='') iItems = iItems.slice(0,iItems.length-1);
    return iItems;
}

function preview() {
	var item_size = $("input[name='item_size']:checked").val();
	var pic_type = "_" + item_size + "x" + item_size + ".jpg";
	item_size = item_size + "px";
	var params = {
		"userTemplet.TEMPLET_ID":$("input[name='t']:checked").val(),
		"userTemplet.SKIN_ID":$("input[name='skin_id']:checked").val(),
		"userTemplet.TITLE":$("input[name='title']").val(),
		"userTemplet.KEY_WORDS":$("input[name='key_words']").val(),
		"userTemplet.ITEM_SIZE":item_size,
		"userTemplet.PIC_TYPE":pic_type,
		"itemsStr":buildItemJsonStr()
    };
    $('#preview_div').html("正在加载中,请等待...");
  	$('#preview_div').dialog("open");
    $.post("preview.action", params,processPreviewResponse, "json");
}

function processPreviewResponse(data,status){
  $('#preview_div').html(data.result);
}

function buildAreaJsonStr() {
	var areaJsonStr = "";
	$("input[name='area']:checked").each(function() {
      	areaJsonStr += $(this).val()+",";
	});
	if(areaJsonStr.length>1) return areaJsonStr.slice(0, -1);
	return areaJsonStr;
}
function sub_persist() {
	var user_rule_type = $("input[name='user_rule_type']").val();
	var rule_type = $("input[name='rule_type']").val();
	var ef = 0;
	if(empty(user_rule_type)) persist(1);
	else if(user_rule_type!==rule_type) {
		$('#confirm_div').dialog("open");
	} else {
		persist(0);
	}
	
}
function persist(ef) {
	if(!check_b4_submit()) return;
	var rule_type = $("input[name='rule_type']").val();
	var start_time = $("input[name='effect_date']").val();
	var end_time = $("input[name='expire_date']").val();
	var ti = $("input[name='t']:checked").val();
	var items_str =  buildItemJsonStr();
	var is_html = $("input[name='is_html']:checked").val();
	
	if(empty(start_time)) start_time = "2000-01-01 00:00:00";
	if(empty(end_time)) end_time = "9999-12-31 23:59:59";
	var item_size = $("input[name='item_size_"+ti+"']:checked").val();
	var pic_type = "_" + item_size + "x" + item_size + ".jpg";
	item_size = item_size + "px";
	var params = {
		"settings.RULE_TYPE":rule_type,
		"settings.START_TEMP":$("input[name='start_temp']").val(),
		"settings.END_TEMP":$("input[name='end_temp']").val(),
		"settings.TEMPLET_ID":ti,
		"settings.SKIN_ID":$("input[name='skin_id_"+ti+"']:checked").val(),
		"settings.TITLE":$("input[name='title_"+ti+"']").val(),
		"settings.KEY_WORDS":$("input[name='key_words_"+ti+"']").val(),
		"settings.ITEM_SIZE":item_size,
		"settings.PIC_TYPE":pic_type,
		"settings.IS_WEATHER":$("input[name='is_weather_"+ti+"']:checked").val(),
		"settings.IS_HTML":is_html,
		"settings.HTML":$("textarea[name='html_text']").val(),
		"settings.S_TIME":"2013-01-01 "+$("input[name='start_time']").val(),
		"settings.E_TIME":"2013-01-01 "+$("input[name='end_time']").val(),
		"settings.START_TIME":start_time,
		"settings.END_TIME":end_time,
		"ef":ef,
    };
    if(is_html=="0" && empty(items_str)) {
    	alert("请选择宝贝！！！");
    	to_step(2);
    	return;
    }
    params["itemJsonStr"] = items_str;
    if(rule_type==="TF_M_USER_RULE_AREA") {
    	var areaJsonStr = buildAreaJsonStr();
    	if(empty(areaJsonStr)) {
    		alert("请选择区域！！！");
    		to_step(1);
    		return ;
    	}
    	params["settings.AREA_IDS"] = areaJsonStr;
    }
    $.post("persist.action", params, processPersistResponse, "json");
}
function processPersistResponse(data){
  if(Number(data.result.code)<0){
    alert(data.result.msg);
  }else{
   	alert("操作已成功！！！");
  	window.location.reload();
  }
}
function display_templet(i) {
	$("div[id*='templet_div_']").css("display", "none");
	$("#templet_div_"+i).css("display", "block");
}

function update_time(selector_type, v, i) {
	var tv = $("input[name='"+selector_type+"']").val();
	var tarray = tv.split(":");
	tarray[i] = v;
	$("input[name='"+selector_type+"']").val(tarray[0]+":"+tarray[1]+":"+tarray[2]);
}

function init_timeslot_selector(selector_type, dv) {
	var tmrry = new Date().format("hh:mm:ss").split(":");
	if(!empty(dv)) tmrry = dv.split(":");
	tmrry[1] = Math.floor(tmrry[1]/5)*5;
	var time_hidden = "<input type='hidden' name='"+selector_type+"' value='"+tmrry[0]+":"+tmrry[1]+":00'/>";
	var hour = "<select onchange=\"update_time('"+selector_type+"', this.value, 0);\" style='width:50px'>";
	var minute = "<select onchange=\"update_time('"+selector_type+"', this.value, 1);\" style='width:50px'>";
	for(var i=0; i<24; i=i+1) {
		hour += "<option value='"+(i<10?"0"+i:i)+"'";
		if(tmrry[0]==i) hour += "selected";
		hour += ">"+(i<10?"0"+i:i)+"</option>";
	}
	hour += "</select>时";
	for(var i=0; i<12; i=i+1) {
		minute += "<option value='"+(5*i<10?"0"+5*i:5*i)+"'";
		if(tmrry[1]==5*i) minute += "selected";
		minute += ">"+(5*i<10?"0"+5*i:5*i)+"</option>";
	}
	minute += "</select>分";
	$("#"+selector_type+"_div").append(time_hidden);
	$("#"+selector_type+"_div").append(hour);
	$("#"+selector_type+"_div").append(minute);
}

function empty(v) {
	if(v===undefined || v===null) return true;
	if(v.trim2Emtpy()=="")
		return true;
	else return false;
}

function check_b4_submit() {
	var flag = true;
	$("input[sub_check='true']").each(function() {
		if(empty($(this).val())) {
			alert($(this).attr("title")+"不能为空！！！");
			flag = false;
			return false;
		}
	});
	return flag;
}

function reserve(type) {
	setvisible(type+'_date_label',type+'_date_div');
	enable(type+"_date");
}

function concel_resv(type) {
	setinvisible(type+'_date_label',type+'_date_div');
	disable(type+"_date");
}

function add_range() {
	var rownum = $("[id*='temp_range_row']").size()+1;
	var range = "<tr id='temp_range_row"+rownum+"'><td class='td1'  align='right'>";
	range += "<a href='#' onclick='delete_range("+rownum+");'>--</a></td>";
	range += "<td class='td2'  align='center'>";
	range += "<span class='temp_input_span'><input type='text' name='start_temp_"+rownum+"'/>℃</span>";
	range += "~";
	range += "<span class='temp_input_span'><input type='text' name='end_temp_"+rownum+"'/>℃</span>";
	range += "</td>"
	range += "<td align='left'></td>";
	$("#temp_range_container").append(range);
}

function system_desin() {
	setinvisible("customed_html_container");
	setvisible("items_list_container", "templet_container");
}

function customed_design() {
	setinvisible("items_list_container", "templet_container");
	setvisible("customed_html_container");
}

function turn_to() {
	var is_html = $("input[name='is_html']:checked").val();
	if(eval(is_html)==0) to_step(3);
	else to_step(4);
}

function delete_range(i) {
	$("#temp_range_row"+i).remove();
}

function disable() {
	var vars = disable.arguments;
	for (var i = 0; i<vars.length; i=i+1){
		$("#"+vars[i]).attr("display", true);
		$("#"+vars[i]).val("");
		$("input[name='"+vars[i]+"']").attr("disabled", true);
		$("input[name='"+vars[i]+"']").val("");
		if($("input[name='"+vars[i]+"']").attr("sub_check"))
			$("input[name='"+vars[i]+"']").attr("sub_check", false);
	}
}

function enable(input_name) {
	var vars = enable.arguments;
	for (var i = 0; i<vars.length; i=i+1){  
		$("#"+vars[i]).attr("display", true);
		$("input[name='"+vars[i]+"']").attr("disabled", false);
		if($("input[name='"+vars[i]+"']").attr("sub_check")!==undefined)
			$("input[name='"+vars[i]+"']").attr("sub_check", true);
	}
}

function setvisible() {
	var vars = setvisible.arguments;
	for (var i = 0; i<vars.length; i=i+1){  
		$("#"+vars[i]).css("display", "block");
	}
}

function setinvisible() {
	var vars = setinvisible.arguments;  
	for (var i=0; i<vars.length; i=i+1){  
		$("#"+vars[i]).css("display", "none");
	}
}

function setImageCellHeight(gridName) { 
   var ids = $("#"+gridName).getDataIDs(); 
   for (var i = 0; i < ids.length; i++) { 
      $("#"+gridName).setRowData(ids[i],false, {height: 60}); 
   } 
}


function buildItemIidStr(div_clazz){
	var clazz = "bePromoted";
	if(!empty(div_clazz)) clazz = div_clazz;
    var iids = "";
    $('.'+clazz).each(function() {
      iids += $(this).attr('id').slice(4)+",";
    });
    if(!empty(iids)) iids = iids.slice(0,iids.length-1);
    return iids;
}

function getCheckboxValues(checkbox_name) {
	var values = "";
	$("input[name='"+checkbox_name+"']:checked").each(function() {
		values += $(this).val()+",";
	});
	if(!empty(values)) values = values.slice(0, values.length-1);
	return values;
}

function formatItemPic(cellvalue, options, rowObject){
  return "<img src='"+cellvalue+"_60x60.jpg'></img>";
}

function formateadorLink(cellvalue, options, rowObject) {
   var title = "<span style='text-decoration:underline;font-size:13px;color:blue;'>"+cellvalue+"</span>";
   return "<a href=http://item.taobao.com/item.htm?id="+ rowObject.iid + " target='_blank'>" + title + "</a>";
}
